import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
  UseInterceptors,
} from '@nestjs/common';
import { TransformInterceptor } from 'src/interceptor/intersform.interceptor';
import {
  createDataDto,
  LianluDataDto,
  QueryLianluDataDto,
  selectLianluByNameDto,
} from './dto/shanghai.dto';
import { ShanghaiService } from './shanghai.service';

@Controller('/shanghai')
@UseInterceptors(new TransformInterceptor())
export class ShanghaiController {
  constructor(private readonly shanghaiService: ShanghaiService) {}

  @Get()
  async getList(@Query() params: QueryLianluDataDto) {
    let res = [] as LianluDataDto[];
    if (params.lianlu_code) {
      res = await this.shanghaiService.getLianluInfoByCode(params.lianlu_code);
    } else {
      res = await this.shanghaiService.getLianluList();
    }
    return {
      message: '获取成功',
      data: res,
    };
  }

  // 根据链路编号获取链路信息
  @Get('/getInfoByCode')
  async getByCode(@Query() param: selectLianluByNameDto) {
    const res = await this.shanghaiService.getLianluInfoByCode(
      param.lianlu_code,
    );
    if (res.length) {
      return {
        data: res[0],
        message: '获取成功',
      };
    } else {
      return {
        data: null,
        message: `${param.lianlu_code}不存在`,
      };
    }
  }

  @Post()
  async create(@Body() data: createDataDto) {
    if (
      (await this.shanghaiService.getLianluInfoByCode(data.lianlu_code)).length
    ) {
      return {
        code: 405,
        message: `${data.lianlu_code}已经存在`,
        data: [],
      };
    } else {
      try {
        this.shanghaiService.createLianlu([data]);
        return {
          message: '添加成功',
        };
      } catch (err) {
        return {
          code: 500,
          message: err,
        };
      }
    }
  }
  // 根据id删除链路
  @Delete(':id')
  async removeLianlu(@Param('id') id: string) {
    if ((await this.shanghaiService.getLianluInfoById(id)).length) {
      const res = await this.shanghaiService.delLianlu(id);
      return { data: res, message: '删除成功' };
    } else {
      return {
        data: [],
        message: '该链路不存在！',
        code: 405,
      };
    }
  }
  // 更新链路信息
  @Put(':id')
  async update(@Param('id') id: string, @Body() data) {
    const res = await this.shanghaiService.updataLianlu(id, data);
    return {
      data: res,
      message: '链路信息更新成功',
    };
  }
}
